#include "stdafx.h"
#include "EffectContainer.h"
#include "Effect.h"
#include "Engine.h"

#define HALT_ON_EFFECT_LOAD_FAIL 1

Graphics::EffectContainer::EffectContainer()
{

}

Graphics::EffectContainer::~EffectContainer()
{

}

Graphics::Effect* Graphics::EffectContainer::GetEffect(const std::string& aFile)
{
	std::string key(aFile);
	Utilities::ToLower(key);

	std::map<std::string, Effect*>::iterator fx = myLoadedEffects.find(key);
	if(fx != myLoadedEffects.end())
	{
		return fx->second;
	}

	return LoadEffect(aFile);
}

Graphics::Effect* Graphics::EffectContainer::LoadEffect(const std::string& aFile)
{
	Effect* effect = new Effect;
	LPD3DXEFFECT fx = NULL;

	DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE;
	dwShaderFlags |= D3DXSHADER_DEBUG;
	dwShaderFlags |= D3DXSHADER_NO_PRESHADER;

	LPD3DXBUFFER errors;
	HRESULT hr = D3DXCreateEffectFromFile(Engine::GetDevice(), GETPATH(aFile).c_str(), NULL, NULL, dwShaderFlags, NULL, &fx, &errors );

	if(FAILED(hr))
	{
		if(errors != 0)
		{
			char* error=NULL;
			error=(char*)errors->GetBufferPointer();
			DL_CRITICAL("Error loading effect");
			DL_Debug::GetDebugInstance()->IncreaseTabCount();
			DL_PRINT(error);
			DL_Debug::GetDebugInstance()->DecreaseTabCount();
#if HALT_ON_EFFECT_LOAD_FAIL
			MessageBox(NULL, error, "Error loading .fx-file", MB_OK);
#endif
		}
		else
		{
			DL_CRITICAL("Error loading effect.");
			DL_Debug::GetDebugInstance()->IncreaseTabCount();
			DL_PRINT(ExtendedString("Supplied filename: \"") << aFile << "\"");
			DL_PRINT(ExtendedString("Resource manager return relative path:  \"") << GETPATH(aFile) << "\"");
			DL_PRINT("No additional information available");
			DL_Debug::GetDebugInstance()->DecreaseTabCount();
		}

		return NULL;
	}

	effect->Init(fx);

	myLoadedEffects.insert(std::make_pair(aFile, effect));

	return effect;
}